import { ipcMain, dialog, screen, BrowserWindow, OpenDialogOptions } from "electron";
import { getAllFile, fromatFileInfo, iterateCompress } from "./utils"
import { CurrentFileList, DealRequire, DealResult, } from "../src/types"
export default function (mainWindow: BrowserWindow) {
  const { width: MaxW, height: MaxH } = screen.getPrimaryDisplay().workAreaSize;
  // 监听请求打开 弹出
  ipcMain.on("openDialog", (event, openType: OpenDialogOptions["properties"], setStateType: string, setStateKey: string) => {
    event.reply("openStatus", true);
    dialog
      .showOpenDialog({
        properties: openType,
      })
      .then((res) => {
        event.reply("setDirState", res, setStateType, setStateKey);
        event.reply("openStatus", false);
      })
      .catch((err) => {
        event.reply("message", "error", err);
        event.reply("openStatus", false);
      });
  });

  // 监听设置窗口
  ipcMain.on("setWindow", (event, type, width, height) => {
    try {
      switch (type) {
        case "big": {
          mainWindow.maximize();
          break;
        }
        case "normal": {
          mainWindow.unmaximize();
          break;
        }
        case "hide": {
          mainWindow.minimize();
          break;
        }
        case "auto": {
          mainWindow.setSize(width, height);
          break;
        }
        case "close": {
          mainWindow.close();
          break;
        }
        default:
          break;
      }
      event.reply("windowSize", type);
    } catch (error) { }
  });

  mainWindow.on("focus", () => {
    console.log(mainWindow.isMaximized());
    const windowSize = mainWindow.isMaximized() ? "big" : "normal";
    mainWindow.webContents.send("windowSize", windowSize);
  });
  mainWindow.on("maximize", () => {
    mainWindow.webContents.send("windowSize", "big");
  });
  mainWindow.on("unmaximize", () => {
    mainWindow.webContents.send("windowSize", "normal");
  });

  // 请求读取文件内容
  ipcMain.on("findDirImg", (event, dir) => {
    event.reply("setFileLoad", true);
    const list = getAllFile(dir).map(fromatFileInfo).filter(Boolean);
    if (list.length === 0) {
      event.reply("message", "warn", "未检测到图片！")
    }
    event.reply("setFileList", list);
    event.reply("setFileLoad", false);
  });

  // 监听 请求解压文件
  ipcMain.on("compressList", (e, filelist: CurrentFileList, dealRequire: DealRequire) => {
    console.log("解压图片");

    const dealResult: DealResult = {
      fail: 0,
      success: 0,
      total: filelist.length,
      isDeal: true,
      successList: [],
      failList: []
    }

    e.reply("compressResult", dealResult)
    iterateCompress(filelist, 0, dealRequire, dealResult, e, (result) => {
      result.isDeal = false
      e.reply("compressResult", result)
    })
  })
};
